package com.augurit.gzcgwsp.ljzyz.web;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.ProcessEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.ljzyz.entity.YwYnBusinfo;
import com.augurit.gzcgwsp.ljzyz.entity.YwYnLjzyzSqb;
import com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService;
import com.augurit.gzcgwsp.ljzyz.service.IYwYnLjzyzShhzService;
import com.augurit.gzcgwsp.ljzyz.service.IYwYnLjzyzSqbService;
import com.augurit.gzcgwsp.ljzyz.web.form.YwYnBusinfoForm;
import com.augurit.gzcgwsp.ljzyz.web.form.YwYnLjzyzSqbForm;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.rqqyjyxk.web.form.YwRqQyjyxkForm;
import com.augurit.gzcgwsp.sendNotice.service.IYwPublicOpinionsService;
import com.augurit.gzcgwsp.wfex.app.doc.IOaDocCodeServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.gzcgwsp.ywcmn.service.IYwComQyxxService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComQyxxForm;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientAction;

@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "yw-yn-ljzyz-shhz.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/gzcgwsp/ljzyz/YwYnLjzyzShhz/YwYnLjzyzShhz.jsp"),
	@Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/ljzyz/YwYnLjzyzShhz/YwYnLjzyzShhz-input.jsp"),
	@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
	@Result(name = WfConstant.MAKE_DOCUMENT, location = "/gzcgwsp/wfex/client/common/make-noline-document.jsp"),
	@Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP)
})
public class YwYnLjzyzShhzAction extends WfBusClientAction<YwYnLjzyzSqbForm>{

    @Autowired
    private IWfServiceEX wfServiceEX;
	@Autowired
	private IYwYnLjzyzShhzService ywYnLjzyzShhzService;
	@Autowired
	private IYwYnLjzyzSqbService ywYnLjzyzSqbService;
	@Autowired
    private ProcessEngine processEngine;
	@Autowired
	private IYwComQyxxService qyxxService;
    @Autowired
    private ISysCodeService syscodeService;
    @Autowired
    private IYwPrintDocService ywPrintDocService;
    @Autowired
	private IYwPublicOpinionsService ywPublicOpinionsService;
    @Autowired
    private IWfBusTemplateService wfBusTemplateService;
    @Autowired
	private IYwYnBusinfoService ywYnBusinfoService;
    @Autowired
    private IWfBusTemplateServiceEX wfBusTemplateServiceEX;
    @Autowired
    private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;
    @Autowired
    private IOaDocCodeServiceEX oaDocCodeServiceEX;
	private YwYnLjzyzSqbForm form;
	private Long id;
	private Long[] checkedIds;
	private Page<YwYnLjzyzSqbForm> page = new Page<YwYnLjzyzSqbForm>(10);
    /**
     * 保存业务并关联流程实例
     */
	@Override
	public String wfBusSave(){
		try{
        if (form.getQyid() == null) {
            YwComQyxxForm qyxxForm = qyxxService.getFormBySqdw(form.getSqdw(),form.getTemplateCode());
            if (qyxxForm != null) {
                WfUtils.renderWfFailtureJson("该企业名称已经存在，请点击选择企业从企业列表中选择该企业！");
                return null;
            }
        }
        String isYsl = super.getParameter("isYsl");
        WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)ywYnLjzyzShhzService, form, YwYnLjzyzSqb.class.getSimpleName());
        
        if (form.getDfsj() == null) {
            String durationExpression = wfServiceEX.getProcDueExpressIonByTaskInstDbid(task.getTaskInstDbid());
            Date dfsj = wfServiceEX.calculateDueDate(form.getSarq(), durationExpression);
            form.setDfsj(dfsj);
            this.save();
        }
        if (StringUtils.isNotBlank(isYsl) && "1".equals(isYsl)) {
            String executionId =  processEngine.getHistoryService().createHistoryTaskQuery().taskId(task.getTaskInstDbid().toString()).uniqueResult().getExecutionId();
            processEngine.getExecutionService().jumpToActivity(executionId, "cksa");
            ywYnLjzyzShhzService.changeYslState(form.getId(), null);
        }
        WfUtils.renderWfBusSaveJson(task, form);
		}catch (Exception e) {
			WfUtils.renderWfFailtureJson("请检查输入内容长度是否过大!");
		}
        return null;
	}
	
	@Override
	public String list() throws Exception {
		ywYnLjzyzShhzService.search(page, form);
		return SUCCESS;
	}

	/**
	 * 制文
	 * @return
	 */
	public String makeDocument() throws Exception{
		  if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
	            String redHeadFilePath = wfBusTemplateServiceEX.getPrintTemplatePath(Long.parseLong(form.getRedHeadFileId()));
	            form.setRedHeadFilePath(redHeadFilePath);
	        }
		    //查询车辆信息
	        List<YwYnBusinfo> list=(List<YwYnBusinfo>) ywYnLjzyzSqbService.getCars(form);
	        String cphm="";
	        for(YwYnBusinfo info:list){
	        	cphm+=info.getCphm()+"、";
	        }
	        form.setCphm(cphm);
	        form.setCarsize(list.size()+"");
	        form.setSlyear(DateUtilsEX.getCurYear());
	        form.setSlmonth(DateUtilsEX.getCurMonth());
	        form.setSlday(DateUtilsEX.getCurDay());
	        String templateCode = getTemplateCode();
	        if(templateCode != null && templateCode.trim().length() > 0){
	            String printTemplatePath = wfBusTemplateServiceEX.getPrintTemplatePath(templateCode, WfTemplateAttachmentRefFormEX.ZHENGWEN_TEMPLATE_TYPE);
	            form.setTemplatePath(printTemplatePath);
	            logger.info("制文打印模版文件printTemplatePath------>"+printTemplatePath);
	            WfTemplateAttachmentRefFormEX wfTemplateAttachmentRefFormEX = (WfTemplateAttachmentRefFormEX)wfTemplateAttachmentRefServiceEX.get(Long.parseLong(form.getZhengwenFileId()));
	            String zhengwenPath = wfTemplateAttachmentRefFormEX.getFilePath() + "/" + wfTemplateAttachmentRefFormEX.getFileRealName();
	            logger.info("制文模版文件路径------>"+printTemplatePath);
	            form.setZhengwenPath(zhengwenPath);
	            form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
	            form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
	            form.setCbyw("建筑垃圾准运证审批");
	            form.setCbyw2("建筑垃圾准运证审批");
	            form.setCbyw3("建筑垃圾准运证审批");
	            form.setCbyw4("建筑垃圾准运证审批");
	            //---获取受理通知书时间---韩修改
	            YwRqQyjyxkForm sltjsForm=new YwRqQyjyxkForm();
	            sltjsForm.setFileCode("sltzs");
	            List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(),sltjsForm.getFileCode(), form.getId());
	            if(ywPrintDocFormList!=null&&ywPrintDocFormList.size()>0){
	            	YwPrintDocForm ywPrintDocForm=ywPrintDocFormList.get(0);
	            	form.setSlDate(DateUtilsEX.convertCommonDate(ywPrintDocForm.getCreatDate()));
	            }
	            Long seq=oaDocCodeServiceEX.getCurSeqAndAddSeq(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),form.getId(),false);
		        if(seq.intValue()<10){
		        	  form.setCurSeq("0"+String.valueOf(seq));
		        }else{
		        	  form.setCurSeq(String.valueOf(seq));
		        }
	            WfUtilsEX.wfBusPrint(form);
	            getRequest().setAttribute("isunified", false);//是否全委统一
	            BaseAction.getRequest().setAttribute("templateFilePath",zhengwenPath);
	            BaseAction.getRequest().setAttribute("fileCode", wfTemplateAttachmentRefFormEX.getFileCode());
	            BaseAction.getRequest().setAttribute("entityId", form.getId());
	            BaseAction.getRequest().setAttribute("templateId", wfTemplateAttachmentRefFormEX.getId());
//	            BaseAction.getRequest().setAttribute("busType", OaFawen.class.getSimpleName());
	        }
	        return WfConstant.MAKE_DOCUMENT; 
	}
	
	/**
	 * �������޸�
	 */
	@Override
	public String input() throws Exception {
	       this.initWfOpinions();
	        getRequest().setAttribute("CurrUserName", this.getLoginUser().getUser().getUserName());
	        Page<YwYnBusinfoForm> ywYnBusinfoFormPage = new Page<YwYnBusinfoForm>(10000);
	        List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
	        if(form.getQyid() != null){
	        	filters.add(new PropertyFilter("EQS_spsx","nsxz"));
	        	filters.add(new PropertyFilter("EQL_qyid",form.getQyid().toString()));
	        	ywYnBusinfoService.search(ywYnBusinfoFormPage, filters);
		        List<YwYnBusinfoForm> ywYnBusinfoFormList = ywYnBusinfoFormPage.getResult();
		        if(ywYnBusinfoFormList.size()>0){
		        	for(int i = 0;i<ywYnBusinfoFormList.size();i++){
		        		YwYnBusinfoForm ywYnBusinfoForm = ywYnBusinfoFormList.get(i);
		        		ywYnBusinfoForm.setDjrqStr(DateUtilsEX.dateTimeToString(ywYnBusinfoForm.getDjrq(),"yyyy-MM-dd"));
		        		ywYnBusinfoForm.setZyzyxqStr(DateUtilsEX.dateTimeToString(ywYnBusinfoForm.getZyzyxq(),"yyyy-MM-dd"));
		        	}	        	
		        }
	        }	        
	        List<SysCodeForm> sqdwlx = syscodeService.getItems("YW_SQDW_LX");
	        List<SysCodeForm> ywHbbm = syscodeService.getItems("ALL_HBBM");
	        getRequest().setAttribute("ywhbbm", ywHbbm);
	        getRequest().setAttribute("sqdwlx", sqdwlx);
	        getRequest().setAttribute("ywYnBusinfoFormPage", ywYnBusinfoFormPage);
			return INPUT;
	}

	/**
	 * �������������޸ĵ�Form����
	 */
	@Override
	public String save() throws Exception {
		ywYnLjzyzShhzService.save(form);
		return RELOAD;
	}

	/**
	 * ɾ��һ����¼
	 */
	@Override
	public String delete() throws Exception {
		ywYnLjzyzShhzService.delete(id);
		return RELOAD;
	}
	
	/**
	 * ɾ�������¼
	 */
	@Override
	public String deleteMore() throws Exception{
		ywYnLjzyzShhzService.delete(checkedIds);
		return RELOAD;
	}
	
	/**
     * 出证
     */
    public String printcz() throws Exception {
        if(form.getId() != null && form.getId() > 0){
            List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getId());
            if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
                return WfConstant.PRINT_DIR;
            }
        }
        return WfUtilsEX.wfBusPrint(form);
    }
	
	/**
	 * ׼��ҳ��ģ��
	 */
	@Override
	protected void prepareModel() throws Exception {
	    String id = super.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			form = ywYnLjzyzShhzService.get(Long.parseLong(id));
		} else {
			form = new YwYnLjzyzSqbForm();
		}		

        if (StringUtils.isBlank(form.getAcceptNo())) {
        	String rq = DateUtilsEX.getYearAndMonthAndDay();
        	form.setAcceptNo("gz26"+rq+"XXXXX");
        }
        if (StringUtils.isBlank(form.getSjr())) {
            form.setSjr(this.getLoginUser().getUser().getUserName());
        }
        if (form.getLarq() == null) {
        	form.setLarq(new Date());            
        }
        
        if (StringUtils.isBlank(form.getCbyw())) {
            WfBusTemplateForm wfBusTemplateForm = wfBusTemplateService.getByTemplateCode(getTemplateCode());
            if (wfBusTemplateForm != null) {
                form.setCbyw(wfBusTemplateForm.getTemplateName());
            }
        }

        if (StringUtils.isBlank(form.getCbbm())) {
            form.setCbbm("余泥处");
        }
        
        if (form.getSqrq() == null) {
            form.setSqrq(new Date());
        }
        if (form.getSarq() == null) {
            form.setSarq(new Date());
        }
        if (form.getCpsj() == null) {
            form.setCpsj(new Date());
        }
	}
	

	public YwYnLjzyzSqbForm getModel() {
		return form;
	}
	
	// ����getter��setter����
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long[] getCheckedIds() {
		return checkedIds;
	}

	public void setCheckedIds(Long[] checkedIds) {
		this.checkedIds = checkedIds;
	}
	
	public Page<YwYnLjzyzSqbForm> getPage() {
		return page;
	}


	public void setPage(Page<YwYnLjzyzSqbForm> page) {
		this.page = page;
	}
}
